package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManipulateGridEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public ManipulateGridEnv() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		String strSQL = "";
		String oper = request.getParameter("oper");			//增刪改查那一種
		final String bssId = "MBMS";
		String subSysId = request.getParameter("subSysId");
		String envId = request.getParameter("envId");
		String result = "";
		final String currentUser = request.getParameter("currentUser");
		
		try {
			/** 判別需進行何種操作 **/
			if ( "del".equalsIgnoreCase(oper) ) {
				strSQL = "DELETE FROM env WHERE envid=? AND bssid=? AND subsysid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, envId);
				ps.setString(2, bssId);
				ps.setString(3, subSysId);
				ps.execute();
				
				wid.keepLogProfile(wid.ENV, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+envId;
			} else if ( "add".equalsIgnoreCase(oper) ) {
				if ( !isDuplicated(bssId,subSysId,envId,conn,ps,rs) ) {
					strSQL = "INSERT INTO env (subsysid,envname,creator,createdDateTime,bssid,envid) VALUES (?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, subSysId);
					ps.setString(2, wid.UI2DB( request.getParameter("envName"),conn.getMetaData().getDatabaseProductName() ) );
					ps.setString(3, currentUser);
					ps.setTimestamp(4, wid.currentTimeStamp());
					ps.setString(5, bssId);
					ps.setString(6, envId);
					ps.execute();
					
					wid.keepLogProfile(wid.ENV, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+envId;
				} else {
					result = envId+" 已存在 !";		
				}
			} else if ( "edit".equalsIgnoreCase(oper) ) {
				int selfClass = 1;
				int preClass = 0;
				
				try {
					if ( wid.isDebug ) { System.out.println("selfTry"); }
					selfClass = Integer.parseInt( request.getParameter("selfClass") );
				} catch ( NumberFormatException e ) {
					if ( wid.isDebug ) { System.out.println("selfCatch"); }
					selfClass = 1;
				}
				try {
					if ( wid.isDebug ) { 
						System.out.println(Integer.parseInt( request.getParameter("preClass") ));
						System.out.println("preTry"); 
					}
					preClass = Integer.parseInt( request.getParameter("preClass") );
					
				} catch ( NumberFormatException e ) {
					if ( wid.isDebug ) { System.out.println("preCatch"); }
					preClass = 0;
					
				}
				
				strSQL = "UPDATE env SET envname=?,webconsolesn=?,preClass=?,selfClass=?,lastUpdator=?,lastUpdatedDateTime=? WHERE subsysid=? AND bssid=? AND envid=?";
				
				if ( wid.isDebug ) {
					System.out.println(strSQL);
					System.out.println("preClass="+preClass);
					System.out.println("selfClass="+selfClass);
				}
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, wid.UI2DB( request.getParameter("envName"),conn.getMetaData().getDatabaseProductName() ));
				ps.setInt(2, Integer.parseInt( request.getParameter("webConsole") ) );
				ps.setInt(3, preClass );
				ps.setInt(4, selfClass );
				ps.setString(5, currentUser);
				ps.setTimestamp(6, wid.currentTimeStamp());
				ps.setString(7, subSysId);
				ps.setString(8, bssId);
				ps.setString(9, envId);
				ps.execute();
				
				wid.keepLogProfile( wid.ENV, wid.UPDATE, currentUser, conn, ps );
				result = "修改完成 "+envId;
			}			
		}  catch (SQLException e) {
			result = "異動"+envId+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			result = "異動"+envId+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			result = "異動"+envId+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if ( rs!= null) { rs.close(); }
				if ( ps!= null) { ps.close(); }
				if ( conn!= null) { conn.close(); }
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		response.getWriter().write(result);		
	}
	
	private boolean isDuplicated(String bssId,String subSysId,String envId,Connection conn,PreparedStatement ps, ResultSet rs) throws SQLException {
		String strSQL = "SELECT COUNT(*) FROM env WHERE bssid=? AND subsysid=? AND envid=?";
		
		ps = conn.prepareStatement(strSQL);
		ps.setString(1, subSysId);
		ps.setString(2, bssId);
		ps.setString(3, envId);
		rs = ps.executeQuery();
		rs.next();

		return rs.getInt(1) == 0?false:true;
	}
}